﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateMaterialForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly string _apiBaseUrl = "https://localhost:7274";
        private readonly long _editId;

        public UpdateMaterialForm(MaterialForm.MaterialModel model)
        {
            InitializeComponent();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
            // 反填
            _editId = model.Id;
            textEditCode.Text = model.MaterialCode;
            textEditName.Text = model.MaterialName;
            textEditMsg.Text = model.MaterialMsg;
            comboBoxEditType.Text = model.MaterialType;
            textEditProcessRoute.Text = model.Routing;
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                Id = _editId,
                MaterialCode = textEditCode.Text,
                MaterialName = textEditName.Text,
                MaterialMsg = textEditMsg.Text,
                MaterialType = comboBoxEditType.Text,
                Routing = textEditProcessRoute.Text,
                UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
            };

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(_apiBaseUrl);
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PutAsync("/api/Material/UpdateMaterial", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("修改成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"修改失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UpdateMaterialForm_Load(object sender, EventArgs e)
        {

        }
    }
}